/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package controller

import (
	"icep/bean/param"
	view2 "icep/bean/view"
	"icep/common/http"
	"icep/common/jwt"

	"github.com/emicklei/go-restful"
)

func (ic *IcepController) InitBaasUser(req *restful.Request, resp *restful.Response) {
	var chainUserParam param.ChainUserParam
	if err := req.ReadEntity(&chainUserParam); err != nil {
		http.Failed(resp, "参数不合法！")
		return
	}

	exist := ic.IcepService.IsBaasUserIdExist(chainUserParam.BaasUserId)
	if exist {
		http.Failed(resp, "baasId已存在")
		return
	}

	err := ic.IcepService.InitBaasUser(chainUserParam)
	if err != nil {
		http.Failed(resp, "初始化失败！")
		return
	}
	http.Ok(resp, "初始化成功")

}

func (ic *IcepController) OAuthLogin(req *restful.Request, resp *restful.Response) {
	clientId := req.QueryParameter("clientId")
	userDetail := ic.IcepService.GetUserByBaasUserId(clientId)
	if userDetail == nil {
		http.Failed(resp, "client id不存在")
		return
	}
	// 生成令牌并返回给客户端
	token := jwt.GenerateToken(userDetail.Id, userDetail.UserType, userDetail.TenantId, userDetail.Phone, userDetail.Mail)
	if token == "" {
		log.Error("failed to generate token")
		http.Failed(resp, "令牌生成失败！")
		return
	}
	loginView := view2.LoginView{Token: token}
	resp.Header().Add("Authorization", token)
	http.OkWithData(resp, "登录成功", loginView)
}
